import store from 'store';
const qnyDomain = 'https://pic.hzdazi.com/';
const qnyUploadUrl = 'https://up-z2.qiniup.com/';
import http from '../api/http.js';
// import compressImage  from './imageutil.js';
let pageList = {};
let util = {
	formartDate() {
		const date = new Date()
		const year = date.getFullYear()
		const month = parseInt(date.getMonth()) + 1 > 9 ? parseInt(date.getMonth()) + 1 : '0' + (parseInt(date
			.getMonth()) + 1)
		const day = date.getDate() > 9 ? date.getDate() : '0' + date.getDate()
		return year + '-' + month + '-' + day
	},
	showLoading(va) {
		uni.showLoading({
			mask: true,
			title: va
		});
	},
	naviTo(url) {
		uni.navigateTo({
			url
		})
	},
	hideLoading() {
		uni.hideLoading();
	},
	showToast(e) {
		uni.showToast({
			title: e,
			mask: true,
			icon: 'none',
			duration: 2000
		});
	},
	setStorage(key, val) {
		uni.setStorageSync(key, val);

		console.log(val);
		// uni.setStorage({
		// 	key: key,
		// 	data: val
		// });
	},
	formatTime(number, format) {
		var formateArr = ['Y', 'M', 'D', 'h', 'm', 's'];
		var returnArr = [];
		var date = new Date(number * 1000);
		returnArr.push(date.getFullYear());
		returnArr.push(until.formatNumber(date.getMonth() + 1));
		returnArr.push(until.formatNumber(date.getDate()));
		returnArr.push(until.formatNumber(date.getHours()));
		returnArr.push(until.formatNumber(date.getMinutes()));
		returnArr.push(until.formatNumber(date.getSeconds()));
		for (var i in returnArr) {
			format = format.replace(formateArr[i], returnArr[i]);
		}
		return format;

	},
	formatNumber(n) {
		n = n.toString()
		return n[1] ? n : '0' + n
	},
	getStorage(key) {
		// let St = '';
		// uni.getStorage({
		// 	key: key,
		// 	success(ret) {
		// 		St = ret.data;
		// 	},
		// 	fail(ret) {
		// 		console.log(ret)
		// 	}
		// });
		console.log(key)
		return uni.getStorageSync(key);
	},
	formatMsgTime(timespan) {
		var dateTime = new Date(timespan * 1000) // 将传进来的字符串或者毫秒转为标准时间
		var year = dateTime.getFullYear() // 将当前编辑的时间转换为年
		var month = dateTime.getMonth() + 1 // 将当前编辑的时间转换为月
		var day = dateTime.getDate() // 将当前编辑的时间转换为天
		var hour = dateTime.getHours() // 将当前编辑的时间转换为小时
		var minute = dateTime.getMinutes() // 将当前编辑的时间转换为分
		// var second = dateTime.getSeconds()// 将当前编辑的时间转换为秒
		var millisecond = dateTime.getTime() // 将当前编辑的时间转换为毫秒
		var now = new Date() // 获取本机当前的时间
		var nowNew = now.getTime() // 将本机的时间转换为毫秒
		var milliseconds = 0
		var timeSpanStr
		milliseconds = nowNew - millisecond //时间差
		if (milliseconds <= 1000 * 60 * 1) { // 小于一分钟展示为刚刚
			timeSpanStr = '刚刚'
		} else if (1000 * 60 * 1 < milliseconds && milliseconds <= 1000 * 60 * 60) { // 大于一分钟小于一小时展示为分钟
			timeSpanStr = Math.round((milliseconds / (1000 * 60))) + '分钟前'
		} else if (1000 * 60 * 60 * 1 < milliseconds && milliseconds <= 1000 * 60 * 60 * 24) { // 大于一小时小于一天展示为小时
			timeSpanStr = Math.round(milliseconds / (1000 * 60 * 60)) + '小时前'
		} else { // 大于一天小于十五天展示位天 (1000 * 60 * 60 * 24 < milliseconds && milliseconds <= 1000 * 60 * 60 * 24 * 15)
			timeSpanStr = Math.round(milliseconds / (1000 * 60 * 60 * 24)) + '天前'
		}
		//  else if (milliseconds > 1000 * 60 * 60 * 24 * 15 && year === now.getFullYear()) {
		// 	timeSpanStr = month + '-' + day + ' ' + hour + ':' + minute
		// } else {
		// 	timeSpanStr = year + '-' + month + '-' + day + ' ' + hour + ':' + minute
		// }
		return timeSpanStr
	},
	timestampToTime(timestamp, day) {
		let date = new Date(timestamp * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
		let Y = date.getFullYear() + '-';
		let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
		let D = this.formatNumber(date.getDate());
		let h = this.formatNumber(date.getHours()) + ':';
		let m = this.formatNumber(date.getMinutes()) + ':';
		let s = this.formatNumber(date.getSeconds());
		if (day == 1) {
			return M + '月' + D + '日'
		} else if (day == 3) {
			return Y + M + '-' + D + ' ' + h + m + s;
		} else if (day == 4) {
			return h + m + s;
		} else {
			return Y + M + '-' + D;
		}
	},
	timeToTimestamp(time) {
		let times = time;
		if (time.indexOf('-') > -1) {
			times = time.replace(/-/g, '/');
		}
		let timestamp = new Date(times).getTime();
		return timestamp;
	},
	gettimes() {
		let date = new Date().getTime();
		let date1 = new Date(date);
		let year = date1.getFullYear();
		let dayt = until.change(date1.getDate());
		let month = (date1.getMonth() + 1 < 10 ? '0' + (date1.getMonth() + 1) : date1.getMonth() + 1);
		let yearmr = year + '-' + month + '-' + dayt;
		return yearmr
	},
	change(t) {
		if (t < 10) {
			return "0" + t;
		} else {
			return t;
		}
	},
	keepTwoDecimalFull(num) { //四舍五入保留2位小数（不够位数，则用0替补）
		var result = parseFloat(num);

		if (isNaN(result)) {
			return false;
		}
		result = Math.round(num * 100) / 100;
		var s_x = result.toString();
		var pos_decimal = s_x.indexOf('.');
		if (pos_decimal < 0) {
			pos_decimal = s_x.length;
			s_x += '.';
		}
		while (s_x.length <= pos_decimal + 2) {
			s_x += '0';
		}
		return s_x;
	},
	getTime(end_time, totalSeconds, type = 1) { // 倒计时
		if (!totalSeconds) {
			// var endDate = new Date(end_time.replace(/-/g, "/"))		// 秒杀结束时间
			var endDate = new Date(end_time) // 秒杀结束时间
			// var nowDate = new Date();
			var nowDate = Math.round(new Date() / 1000) // 获取当前时间
			// var totalSeconds = parseInt((endDate - nowDate) / 1000)
			var totalSeconds = parseInt(endDate - nowDate)
		}

		// 天数（转换成字符串类型，以防网不好的情况下，出现now）
		var day = totalSeconds / (60 * 60 * 24);
		var days = null;
		days = day.toString().split(".")[0];
		// 取模（余数）
		var modulo = totalSeconds % (60 * 60 * 24);
		// 小时数
		var hours = Math.floor(modulo / (60 * 60));
		modulo = modulo % (60 * 60);
		// 分钟
		var minutes = Math.floor(modulo / 60);
		// 秒
		var seconds = modulo % 60;

		// 判断时间是否大于10,否则加0
		days = days < 10 ? "0" + days : days;
		hours = hours < 10 ? "0" + hours : hours;
		minutes = minutes < 10 ? "0" + minutes : minutes;
		seconds = seconds < 10 ? "0" + seconds : seconds;

		if (type == 1) {
			var time = days + '天' + hours + '时' + minutes + '分' + seconds + '秒';
		} else if (type == 2) {
			var time = days + ':' + hours + ':' + minutes + ':' + seconds;
		}

		return time;
	},
	tel(val) { // 手机号后面四位换成星号
		var tel = "" + val;
		var reg = /^(\d{3})\d{4}(\d{4})$/;
		tel = tel.replace(reg, "$1****$2");
		return tel;
	},
	// const device = uni.getSystemInfoSync();
	// const src = await compressImageHandler(file);
	// async function compressImageHandler(src){
	// 	console.log('platform==='+device.platform)
	// 	const tempPath = await compressImage(src,device.platform);
	// 	console.log('tempPath-----'+tempPath);
	// 	return tempPath
	// }
	// return;
	uploadService(file, callback,type) {
		if (!file) return;
		type = type?type:file.type?(file.type.split('/')[1]?file.type.split('/')[1]:'png'):'png';
		this.uploadServiceDo(file,'',callback,type); // 上传Base64编码的图片
		// const reader = new FileReader();
		// reader.readAsDataURL(file);
		// reader.onload = (e) => {
		// 	const base64 = e.target.result; // 这里的base64就是图片的Base64编码
		// 	this.uploadServiceDo(file,'',callback,type); // 上传Base64编码的图片
		// };
	},
	uploadFile(file, callback,type) {
		if (!file) return;
		this.uploadServiceDo(file,'',callback,type);
	},
	uploadServiceDo(file,base64,callback,type) {
		uni.showLoading({
			title:'上传中...'
		})
		let data = {
			filename:base64,
			suffix:type?type:''
		}
		http('/oss/url',data).then(res=>{
			// console.log(res)
			let e = res.data;
			
			const formData = new FormData()
			formData.append('key', e.key)
			formData.append('OSSAccessKeyId', e.id)
			formData.append('policy', e.policy)
			formData.append('signature', e.signature)
			formData.append('file', file)
			const xhr = new XMLHttpRequest()
			const uploadRes =  new Promise((resolve, reject) => {
				xhr.open('POST', e.host, true)
				xhr.onload = () => {
					if (xhr.status === 200 || xhr.status === 204) {
						resolve(xhr.responseText)
					} else {
						reject(new Error(`上传失败: ${xhr.status}`))
					}
				}
				xhr.onerror = () => {
					reject(new Error('上传请求失败'))
				}
				xhr.send(formData)
			})
			console.log('上传成功', uploadRes)
			uploadRes.then(res=>{
				console.log('上传成功2', res)
				if (callback) callback(e.url);
			})
			uni.hideLoading();
		})
	},
	/**
	 * 计算两个经纬度点之间的距离（单位：米）
	 * @param {number} lat1 第一个点的纬度
	 * @param {number} lon1 第一个点的经度
	 * @param {number} lat2 第二个点的纬度
	 * @param {number} lon2 第二个点的经度
	 * @returns {number} 两点之间的距离（米）
	 */
	calculateDistance(lat1, lon1, lat2, lon2) {
		lat1 = lat1?Number(lat1):0;
		lon1 = lon1?Number(lon1):0;
		lat2 = lat2?Number(lat2):0;
		lon2 = lon2?Number(lon2):0;
	    const R = 6371e3; // 地球半径（米）
	    const φ1 = lat1 * Math.PI / 180; // 纬度1，转换为弧度
	    const φ2 = lat2 * Math.PI / 180; // 纬度2，转换为弧度
	    const Δφ = (lat2 - lat1) * Math.PI / 180; // 纬度差
	    const Δλ = (lon2 - lon1) * Math.PI / 180; // 经度差
	
	    const a = Math.sin(Δφ / 2) * Math.sin(Δφ / 2) +
	              Math.cos(φ1) * Math.cos(φ2) *
	              Math.sin(Δλ / 2) * Math.sin(Δλ / 2);
	    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
	
	    const distance = R * c; // 最终距离（米）
	    return distance;
	},
	uploadQNY: async function(file, callback, fileType) {
		console.log(file)
		let comFile;
		// #ifndef H5
		if (!fileType) { //压缩图片  可以不传
			uni.compressImage({
				src: file,
				quality: 80,
				success: res => {
					console.log(res.tempFilePath);
					comFile = res.tempFilePath;
				}
			})
		}
		// #endif
		http("v1/GetSettingQinToken", {}).then(e => { //请求后台 获取token 上传图片
			if (e.status == 800000) {
				uni.showLoading({
					title: "上传中...",
					mask: true
				});
				var key = "dazi_" + new Date().getTime(); //图片的随机名字

				uni.uploadFile({ //上传  七牛云
					url: qnyUploadUrl, //上传的地址
					filePath: comFile ? comFile : file, //图片路径  
					formData: {
						'key': key,
						'token': e.data.token
					},
					name: 'file',
					success: (
					res) => { //成功了之后  七牛云上就有这张图  直接七牛域名加key返回去  就行了   如果是传到服务器后台  喊后台返路径就行
						uni.hideLoading();
						var data = qnyDomain + key; //拼接路径
						if (typeof res.data == 'string') {
							data = qnyDomain + JSON.parse(res.data).key;
						}

						if (callback) callback(data); //回调函数返回路径
						if (!data.key) {
							// #ifdef H5 || MP-WEIXIN

							if (res.data.mess) {
								uni.showToast({
									icon: 'none',
									title: data.mess
								})
							}
							// #endif 
							// #ifdef APP-PLUS
							plus.nativeUI.toast(data.mess)
							// #endif 
						}
					},
					fail: (res) => {
						uni.hideLoading();
						uni.showToast({
							icon: 'none',
							title: '上传失败'
						})
						// console.log(res)
					}
				});
			}
		})
	},
	reloadCurrentPage: function(_self, isTab = true) {
		console.log('arrddd');
		// #ifdef APP-PLUS  
		console.log(plus.os.name)
		if (plus.os.name === 'iOS') {
			var route = _self.$scope.route;
			var data = _self.$scope.options && _self.$scope.options.data;
			var url = '/' + route
			if (data) {
				url = '/' + route + '?data=' + data
			}
			var isRecovery = true;
			let newTime = Date.now();
			console.log(newTime)
			if (pageList[url]) {
				console.log('有pageList[url]--------');
				const query = uni.createSelectorQuery().in(_self);
				//这里select()中替换为自己的样式class名称  
				query.select('.container_pages').fields({
					size: true
				}, data => {
					isRecovery = false;
				}).exec();
				setTimeout(() => {
					if (isRecovery) {
						console.log('没获取到节点');
						//如果获取不到节点  
						//确保只刷新一次  
						if (newTime - pageList[url] > 3000) {
							//超过3秒才重新刷新，这里设置几秒就行，目的是防止无限刷新  
							//因为刷新后页面肯定会出来，但是立马再次调用该方法不一定能获取节点  
							pageList[url] = newTime;
							if (isTab) {
								uni.reLaunch({
									url
								})
							} else {
								uni.redirectTo({
									url
								})
							}
						}
					}
				}, 600)
			} else {
				console.log('没有pageList[url]--------');
				pageList[url] = newTime;
			}
		}
		// #endif  
	},
	bigNumberTransform(value) {
		value = Number(value);
		const newValue = ['', '', ''];
		let fr = 1000;
		let num = 3;
		let text1 = '';
		let fm = 1;
		while (value / fr >= 1) {
			fr *= 10;
			num += 1;
			console.log('数字', value / fr, 'num:', num);
		}
		//  if (num <= 4) { // 千
		// newValue[0] = parseFloat(value / 1000).toFixed(2) + '';
		//    // newValue[0] = parseInt(value / 1000) + '';
		//    newValue[1] = '千';
		//  } else 
		if (num <= 8) { // 万
			text1 = parseInt(num - 4) / 3 > 1 ? '千万' : '万';
			// tslint:disable-next-line:no-shadowed-variable
			fm = text1 === '万' ? 10000 : 10000000;
			if (value % fm === 0) {
				newValue[0] = parseInt(value / fm) + '';
			} else {
				newValue[0] = parseFloat(value / fm).toFixed(1) + '';
			}
			newValue[1] = text1;
		} else if (num <= 16) { // 亿
			text1 = (num - 8) / 3 > 1 ? '千亿' : '亿';
			text1 = (num - 8) / 4 > 1 ? '万亿' : text1;
			text1 = (num - 8) / 7 > 1 ? '千万亿' : text1;
			// tslint:disable-next-line:no-shadowed-variable
			fm = 1;
			if (text1 === '亿') {
				fm = 100000000;
			} else if (text1 === '千亿') {
				fm = 100000000000;
			} else if (text1 === '万亿') {
				fm = 1000000000000;
			} else if (text1 === '千万亿') {
				fm = 1000000000000000;
			}
			if (value % fm === 0) {
				newValue[0] = parseInt(value / fm) + '';
			} else {
				newValue[0] = parseFloat(value / fm).toFixed(1) + '';
			}
			newValue[1] = text1;
		}
		if (value < 10000) {
			newValue[0] = value + '';
			newValue[1] = '';
		}
		return newValue.join('');
	},
	shareMiniProgram(obj) {
		uni.share({
			provider: 'weixin',
			scene: "WXSceneSession",
			type: 5,
			imageUrl: 'http://dz.cqmomo.top/static/img/logo.png',
			title: '搭子',
			miniProgram: {
				id: 'gh_cf3767b16533',
				path: obj.path,
				type: 0, //0-正式版； 1-测试版； 2-体验版。
				webUrl: 'http://uniapp.dcloud.io'
			},
			success: ret => {
				console.log(JSON.stringify(ret));
			},
			fail: (rej) => {
				console.log(rej)
			}
		});
	},
	shareWx(obj) {
		let str = {
			imageUrl: 'http://dz.cqmomo.top/static/img/logo.png',
			title: '搭子',
			path: obj.path
		}
		return str;
	},
	onFeedTap() { //手机振动
		let platform = uni.getSystemInfoSync().platform
		// #ifdef APP-PLUS
		if (platform == "ios") {
			let UIImpactFeedbackGenerator = plus.ios.importClass('UIImpactFeedbackGenerator');
			let impact = new UIImpactFeedbackGenerator();
			impact.prepare();
			impact.init(1);
			impact.impactOccurred();
		}
		if (platform == "android") {
			uni.vibrateShort();
		}
		// #endif
	},
	openLocal(info) {
		uni.openLocation({
			latitude: info.latitude,
			longitude: info.longitude,
			name: info.description,
			success: function() {
				console.log('success');
			}
		});
	},
	dateTimeFliter(time, part = 0, dateComplete = true, timeComplete = true, dateConnector = '-',
		timeConnector = ':', hour12 = false) {
		let year = time.getFullYear()
		let month = time.getMonth() + 1
		let day = time.getDate()
		let hour = time.getHours()
		let minute = time.getMinutes()
		let second = time.getSeconds()
		let dateStr = ''
		let timeStr = ''
		//转换日期
		if (dateComplete) { //添0补齐
			if (month < 10) {
				month = '0' + month
			}
			if (day < 10) {
				day = '0' + day
			}
		}
		dateStr = year + dateConnector + month + dateConnector + day
		//转换时间
		//修改小时制
		if (hour12) {
			if (hour > 12) {
				hour = hour - 12
				if (timeComplete) {
					if (hour < 10) {
						hour = '下午 ' + '0' + hour
					} else {
						hour = '下午 ' + hour
					}
				}
			} else {
				if (timeComplete) {
					if (hour < 10) {
						hour = '上午 ' + '0' + hour
					} else {
						hour = '上午 ' + hour
					}
				}
			}
		}
		//判断分钟与秒
		if (timeComplete) { //添0补齐
			if (minute < 10) {
				minute = '0' + minute
			}
			if (second < 10) {
				second = '0' + second
			}
		}
		timeStr = hour + timeConnector + minute + timeConnector + second
		//合成输出值
		if (part == 0) {
			return dateStr + ' ' + timeStr
		} else if (part == 1) {
			return dateStr
		} else if (part == 2) {
			return timeStr
		}
		return '传参有误'
	},
	checkPermission() { //title，权限未开启提示的消息
		return new Promise((resolve) => {
			plus.android.requestPermissions(
				["android.permission.ACCESS_FINE_LOCATION"],
				function(resultObj) {
					console.log(resultObj)
					if (resultObj.granted.length <
						1) { //resultObj.granted是授权的权限，是一个数组，你可以直接判断长度也可以拿出来单独判断
						// uni.showToast({
						//       icon: "none",
						//       title,
						//   });
						resolve(false)
						// let timer1 = setTimeout(() => { //没有开对应的权限，打开app的系统权限管理页
						//     var Intent = plus.android.importClass("android.content.Intent");
						//     var Settings = plus.android.importClass("android.provider.Settings");
						//     var Uri = plus.android.importClass("android.net.Uri");
						//     var mainActivity = plus.android.runtimeMainActivity();
						//     var intent = new Intent();
						//     intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
						//     var uri = Uri.fromParts("package", mainActivity.getPackageName(), null);
						//     intent.setData(uri);
						//     mainActivity.startActivity(intent);
						//     clearTimeout(timer1)
						//     timer1 = null
						// }, 1000)
					} else {
						resolve(true)
					}
				}
			);
		})
	},
	isWeiXin() {
	  let ua = window.navigator.userAgent.toLowerCase();
	  // console.log(ua); // mozilla/5.0 (iphone; cpu iphone os 9_1 like mac os x) applewebkit/601.1.46 (khtml, like gecko)version/9.0 mobile/13b143 safari/601.1
	  if (String(ua.match(/MicroMessenger/i)) === 'micromessenger') {
	    return true;
	  } else {
	    return false;
	  }
	},
	formatBytes(bytes, decimals = 2) {
	  if (bytes === 0) return '0 Bytes'
	  const k = 1024
	  const dm = decimals < 0 ? 0 : decimals
	  const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
	  const i = Math.floor(Math.log(bytes) / Math.log(k))
	  return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + '' + sizes[i]
	}
}

export default util